const Jimp = require('jimp')
const replaceColor = require('replace-color')

export function imageClipper(imgPathOrBuffer, outputPath?): Promise<{
  buffer?: Buffer,
  path?: string,
  w: number,
  h: number
}> {
  return new Promise((resolve, reject) => {
    try {
      Jimp.read(imgPathOrBuffer, (errOnRead, jimpObject) => {
        if (errOnRead) return reject(errOnRead)
        jimpObject
          // crop same color borders
          .autocrop({
            tolerance: .5,
            cropOnlyFrames: false
          })
          .getBuffer(Jimp.MIME_PNG, (errOn2Buf, buffer) => {
            if (errOn2Buf) return reject(errOn2Buf)
            // replace #FFF to transparent
            replaceColor({
              image: buffer,
              colors: {
                type: 'hex',
                targetColor: '#FFFFFF',
                replaceColor: '#00000000'
              }
            }, (errOnReplace, clipedObject) => {
              if (errOnReplace) return reject(errOnReplace)
              const h = clipedObject.getHeight()
              const w = clipedObject.getWidth()

              // write in png
              if (outputPath) {
                clipedObject.write(outputPath)
                return resolve({ path: outputPath, h, w })
              }

              // or return buffer
              clipedObject
                .getBuffer(Jimp.MIME_PNG, (errOn2PngBuf, buffer) => {
                  if (errOn2PngBuf) return reject(errOn2PngBuf)
                  resolve({ buffer, h, w })
                })
            })
          })
      })
    } catch (err) {
      reject(err)
    }
  })
}
